/*
    The MIT License

    Copyright (c) 2010 IFMO/GameDev Studio

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*/

#include "ge_local.h"

/*-----------------------------------------------------------------------------
	Animation track :
-----------------------------------------------------------------------------*/

//
//	EAnimTrack::EAnimTrack
//
EAnimTrack::EAnimTrack( void )
{
	SetFPS(1);
}


//
//	EAnimTrack::~EAnimTrack
//
EAnimTrack::~EAnimTrack( void )
{

}


//
//	EAnimTrack::SetTrackSize
//
void EAnimTrack::SetTrackSize( uint curve_num, uint length )
{
	curves.clear();
	curves.resize( curve_num );
	
	for (uint i=0; i<curves.size(); i++) {
		curves[i].samples.resize( length );
	}
}


//
//	EAnimTrack::GetTrackLength
//
uint EAnimTrack::GetTrackLength( void ) const
{
	if (curves.empty()) {
		return 0;
	} else {
		return curves[0].samples.size();
	}
}


//
//	EAnimTrack::GetCurveNum
//
uint EAnimTrack::GetCurveNum( void ) const
{
	return curves.size();
}


//
//
//
void EAnimTrack::SetCurveParent( uint child_curve, uint parent_id )
{
	ASSERT( child_curve < GetCurveNum() );
	curves[ child_curve ].parent_id	=	parent_id;
}


//
//
//
uint EAnimTrack::GetCurveParent( uint child_curve ) const
{
	ASSERT( child_curve < GetCurveNum() );
	return curves[ child_curve ].parent_id;
}


//
//	EAnimTrack::SetCurveName
//
void EAnimTrack::SetCurveName( uint curve, const EString &name )
{
	ASSERT( curve < GetCurveNum() );
	curves[ curve ].name = name;
}


//
//	EAnimTrack::GetCurveName
//
EString EAnimTrack::GetCurveName( uint curve ) const
{
	ASSERT( curve < curves.size() );
	return curves[ curve ].name;
}


//
//	EAnimTrack::GetCurveByName
//
uint EAnimTrack::GetCurveByName( const EString &name ) const
{
	for (uint i=0; i<GetCurveNum(); i++) {
		if (GetCurveName(i)==name) {
			return i;
		}
	}
	return (uint)(-1);
}


//
//	EAnimTrack::SetSample
//
void EAnimTrack::SetSample( uint curve, uint sample, const EPoint &pos, const EQuaternion &orient )
{
	ASSERT( curve < GetCurveNum() );
	ASSERT( sample < GetTrackLength() );
	
	curves[curve].samples[sample].translate		=	pos;
	curves[curve].samples[sample].orient		=	orient;
}



//
//	EAnimTrack::GetSample
//
void EAnimTrack::GetSample( uint curve, int sample, EPoint &pos, EQuaternion &orient, bool repeat ) const
{
	ASSERT( curve < GetCurveNum() );
	ASSERT( GetTrackLength()>0 );
	
	if (repeat) {
		sample	=	sample % GetTrackLength();
	} else {
		sample	=	clamp<int>(sample, 0, GetTrackLength()-1);
	}
	
	pos		=	curves[curve].samples[sample].translate;
	orient	=	curves[curve].samples[sample].orient;
}


//
//	EAnimTrack::LerpSamples
//
void EAnimTrack::LerpSamples( uint curve, int sample0, int sample1, float frac, EPoint &pos, EQuaternion &orient, bool repeat ) const
{
	ASSERT( curve < GetCurveNum() );
	ASSERT( GetTrackLength()>0 );

	EPoint		p0, p1;
	EQuaternion	q0, q1;
	
	GetSample( curve, sample0, p0, q0, repeat );
	GetSample( curve, sample1, p1, q1, repeat );
	
	pos		=	EMath::Lerp ( p0, p1, frac );
	orient	=	EMath::SLerp( q0, q1, frac );
}


//
//	EAnimTrack::LerpSamples
//
void EAnimTrack::LerpSamples( uint curve, float frac_sample, EPoint &pos, EQuaternion &orient, bool repeat ) const
{
	ASSERT( curve < GetCurveNum() );
	ASSERT( GetTrackLength()>0 );

	int		s0		=	(int)floor( frac_sample );
	int		s1		=	(int)ceil( frac_sample );
	float	frac	=	EMath::Frac( frac_sample );

	LerpSamples( curve, s0, s1, frac, pos, orient, repeat );
}


//
//	EAnimTrack::GetSampleAtTime
//
void EAnimTrack::GetSampleAtTime( uint curve, float time, EPoint &pos, EQuaternion &orient, bool repeat ) const
{
	LerpSamples( curve, time * frames_per_second, pos, orient, repeat );
}


//
//	EAnimTrack::Clone
//
IPxAnimTrack EAnimTrack::Clone( void ) const
{
	IPxAnimTrack	track	=	ge()->CreateAnimTrack();
	EAnimTrack		*ptrack	=	track.to<EAnimTrack>();	
	
	*ptrack		=	*this;
	
	return track;
}


//
//	EAnimTrack::WriteXML
//
void EAnimTrack::WriteXML( rapidxml::xml_node<> *xnode ) const
{
	xml_document<>	*xdoc = xnode->document();
	xml_node<>	*xtrackinfo	=	xdoc->allocate_node(node_element, "trackinfo");
	
	xnode->append_node( xtrackinfo );
	xml_add_attr<char>( xtrackinfo, "fps",		va("%g", frames_per_second) );
	xml_add_attr<char>( xtrackinfo, "curves",	va("%d", GetCurveNum()) );
	xml_add_attr<char>( xtrackinfo, "samples",	va("%d", GetTrackLength()) );
	
	for (uint curve=0; curve < GetCurveNum(); curve++) {
		
		xml_node<> *xcurve	=	xdoc->allocate_node(node_element, "curve");
		xnode->append_node( xcurve );
		
		xml_add_attr<char>( xcurve, "parent_id", va("%d", (int)GetCurveParent(curve)) );
		xml_add_attr<char>( xcurve, "name",		GetCurveName(curve).CStr() );
		
		for (uint sample=0; sample<GetTrackLength(); sample++) {
			xml_node<> *xsample	=	xdoc->allocate_node(node_element, "sample");
			xcurve->append_node( xsample );
			
			EPoint		p;
			EQuaternion	q;
			
			GetSample( curve, sample, p, q, false );
			
			xml_add_attr<char>( xsample, "p", va("%g %g %g %g", p.x, p.y, p.z, p.w) );
			xml_add_attr<char>( xsample, "q", va("%g %g %g %g", q.x, q.y, q.z, q.w) );
		}
	}
}


//
//	EAnimTrack::ReadXML
//
void EAnimTrack::ReadXML( rapidxml::xml_node<> *xnode )
{
	xml_node<>	*xtrackinfo	=	xnode->first_node("trackinfo");
	
	uint curve_num	=	0;
	uint sample_num	=	0;
	
	if (xtrackinfo) {
		xml_attribute<>	*xfps		=	xtrackinfo->first_attribute("fps");
		xml_attribute<>	*xcurves	=	xtrackinfo->first_attribute("curves");
		xml_attribute<>	*xsamples	=	xtrackinfo->first_attribute("samples");
		
		if (xfps) {
			SetFPS( atof(xfps->value()) );
		} else {
			RUNTIME_ERROR("missing XML <trackinfo> attribute: fps");
		}
		
		if (!xcurves) {
			RUNTIME_ERROR("missing XML <trackinfo> attribute: curves");
		}
		if (!xsamples) {
			RUNTIME_ERROR("missing XML <trackinfo> attribute: samples");
		}

		curve_num	=	atoi( xcurves->value() );		
		sample_num	=	atoi( xsamples->value() );	
		
		SetTrackSize( curve_num, sample_num );
			
	} else {
		RUNTIME_ERROR("missing XML node : <trackinfo>");
	}
	
	xml_node<>	*xcurve;
	xml_node<>	*xsample;
	
	uint curve	=	0;
	for (xcurve = xnode->first_node("curve"); xcurve; xcurve = xcurve->next_sibling("curve"), curve++) {
	
		xml_attribute<>	*xparent_id	=	xcurve->first_attribute("parent_id");
		xml_attribute<>	*xname		=	xcurve->first_attribute("name");
		
		if (xparent_id) {
			SetCurveParent( curve, atoi(xparent_id->value()) );
		} else {
			RUNTIME_ERROR("missing XML <curve> attribute: parent_id");
		}
	
		if (xname) {
			SetCurveName( curve, xname->value() );
		} else {
			RUNTIME_ERROR("missing XML <curve> attribute: name");
		}
	
		uint sample	=	0;
		for (xsample = xcurve->first_node("sample"); xsample; xsample = xsample->next_sibling("sample"), sample++) {
			EPoint		p	=	EPoint::FromString( xml_get_attr<char>(xsample, "p", "0 0 0 1") );
			EQuaternion	q	=	EQuaternion::FromString( xml_get_attr<char>(xsample, "q", "0 0 0 1") );
			SetSample( curve, sample, p, q );
		}
	}
	
}


/*-----------------------------------------------------------------------------
	Animation blending :
-----------------------------------------------------------------------------*/

//
//	EAnimTrack::BuildAnimFrame
//
void EAnimTrack::BuildAnimFrame( const IPxTriMesh mesh, float frac_sample, bool repeat )
{
	CheckCompatibilityWithMeshJoints( mesh );

	frame.resize( GetCurveNum() );
	frame.reserve( frame.size() );
	
	for (uint i=0; i<GetCurveNum(); i++) {
		LerpSamples( i, frac_sample, frame[i].translate, frame[i].orient, repeat );
	}
}


//
//	EAnimTrack::AddTransform
//
void EAnimTrack::AddTransform( uint curve, const EVector &translate, const EQuaternion &rotate )
{
	ASSERT( curve < GetCurveNum() );
	if (frame.empty()) {
		LOG_WARNING("EAnimTrack::AddTransform() : frame is not built");
	}	
	
	frame[ curve ].translate	=	frame[ curve ].translate	+	translate;
	frame[ curve ].orient		=	frame[ curve ].orient		*	rotate;
}


//
//	EAnimTrack::BuildGlobalMatricies
//
EMatrix *EAnimTrack::BuildGlobalMatricies( const IPxTriMesh mesh )
{
	if (frame.empty()) {
		LOG_WARNING("EAnimTrack::BuildGlobalMatricies() : frame is not built");
	}	
	
	matricies.resize( frame.size() );
	matricies.reserve( matricies.size() );
	
	std::vector<EMatrix>	inv_bind_xforms;
	std::vector<EMatrix>	local_xforms;
	inv_bind_xforms.resize( frame.size() );
	local_xforms.resize( frame.size() );
	
	//	build bind matricies :
	for (uint i=0; i<inv_bind_xforms.size(); i++) {
		const EJoint	*j	=	mesh->GetJoint(i);
		uint parent_id		=	curves[i].parent_id;
		
		EMatrix		bind	=	EMatrix::FromPose( EPoint(j->bind_pos), j->bind_orient );
		
		inv_bind_xforms[i]	=	bind.AffineInverse();
	}
	
	//	build local matricies :
	for (uint i=0; i<local_xforms.size(); i++) {
		const EJoint	*j		=	mesh->GetJoint(i);
		EMatrix			jxform	=	EMatrix::FromPose( EPoint(frame[i].translate), j->orient * frame[i].orient );
		local_xforms[i]			=	jxform;
	}
	
	//	build global matricies :	
	for (uint i=0; i<matricies.size(); i++) {
		uint parent_id		=	curves[i].parent_id;

		if (parent_id==-1) {
			matricies[i]	=	local_xforms[i];
		} else {
			matricies[i]	=	local_xforms[i] * matricies[parent_id];
		}		
	}
	
	for (uint i=0; i<matricies.size(); i++) {
		matricies[i]	=	inv_bind_xforms[i] * matricies[i];
	}
	
	return &matricies[0];
}


//
//	EAnimTrack::CheckCompatibilityWithMeshJoints
//
void EAnimTrack::CheckCompatibilityWithMeshJoints( const IPxTriMesh mesh )
{
	uint n_mesh_joints	=	mesh->GetJointNum();
	uint n_curves		=	GetCurveNum();
	
	if (n_mesh_joints!=n_curves) {
		LOG_WARNING("mesh and track have different number of joints");
		return;
	}
	
	for (uint i=0; i<n_curves; i++) {
		const EJoint *j	=	mesh->GetJoint(i);
		
		if (j->name!=GetCurveName(i)) {
			LOG_WARNING("joint [%d] and curve[%d] have different names '%s' nad '%s'", i, i, j->name.CStr(), GetCurveName(i).CStr());
		}
		
		if (j->parent_index!=GetCurveParent(i)) {
			LOG_WARNING("joint [%d] and curve[%d] have different parent ID", i, i);
		}
	}
}



